package org.example.designPattern.creation.prototype;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DeepCopy implements Serializable {

    private String name;
    private List<String> arrayList = new ArrayList<>();


    public DeepCopy(){
        System.out.println("构造方法执行了！");
        this.name = "qq";
        this.arrayList.add("可怜、无助");
    }

    @Override
    public String toString() {
        return "ShallowCopy{" +
                "name='" + name + '\'' +
                ", arrayList=" + arrayList +
                '}';
    }

    public void setName(String name) {
        this.name = name;
    }

    public void addList(String val) {
        this.arrayList.add(val);
    }

    @Override
    protected  DeepCopy clone() {
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutput = new ObjectOutputStream(byteArrayOutputStream);
        ){
            objectOutput.writeObject(this);
            try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            ){
                DeepCopy o = (DeepCopy)objectInputStream.readObject();
                return o;
            }
        }catch (IOException | ClassNotFoundException ioException){
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        DeepCopy deepCopy = new DeepCopy();
        System.out.println("第一次查看shallowCopy:" + deepCopy);

        System.out.println("即将开始浅拷贝");
        DeepCopy clone = deepCopy.clone();

        System.out.println(clone == deepCopy);
        clone.setName("胆小、懦弱");
        clone.addList("胆小、懦弱");
        System.out.println("第二次查看shallowCopy:" + deepCopy);
        System.out.println("拷贝类：" + clone);
    }
}
